package com.llyb.chap09;

public class VolatileOrderDemo {

    //保证有序性(禁止指令重排)
     static int a, b;
    static int x, y;

    //第18848次打印：x=0, y=0     说明JVM优化器对指令进行重排序。
    public static void main(String[] args) throws InterruptedException {

        int i = 0; //记录循环次数
        while (true) {
            i++;
            a = b = x = y = 0;

            //情况1：thread1先thread2后         a = 1  x = 0  b = 1  y = 1     x,y = [0,1]
            //情况2：thread2先thread1后         b = 1  y = 0  a = 1  x = 1     x,y = [1,0]
            //情况3：thread1和thread2代码交叉执行                                x,y = [1,1]
            Thread thread1 = new Thread(() -> {
                a = 1;
                x = b;
            }, "");

            Thread thread2 = new Thread(() -> {
                b = 1;
                y = a;
            }, "");

            thread1.start();
            thread2.start();

            thread1.join();
            thread2.join();

            System.out.println("第" + i + "次打印：x=" + x + ", y=" + y);

            if (x == 0 && y == 0) {
                break;
            }
        }
    }
}